import { Menu, Layout } from "antd"
import React, { ReactNode, useEffect, useState } from "react"
import { UserOutlined, UsergroupDeleteOutlined, BarChartOutlined } from "@ant-design/icons"
import styles from "./index.module.scss"
import { useHistory } from "react-router-dom"
// import { ItemType } from "antd/lib/menu/hooks/useItems"
import { http } from "@/utils/http"
import { menuItemType } from "@/types"

const iconList: { [propName: string]: ReactNode } = {
  "/home/user-center": <UserOutlined />,
  "/home/user-panel": <UsergroupDeleteOutlined />,
  "/home/data-panel": <BarChartOutlined />,
}

const SideMenu: React.FC = () => {
  const [collapsed] = useState(false)
  const [menuItemList, setMenuItemList] = useState<menuItemType[]>([])
  const history = useHistory()
  const [selectedKeys, setSelectedKeys] = useState<string[]>([])

  useEffect(() => {
    http
      .get("/get/menus")
      .then(({ data: res }) => {
        const items = res.data as menuItemType[]
        setMenuItemList(
          items.map((menuItem) => ({
            ...menuItem,
            icon: iconList[menuItem?.key!],
            disabled: !menuItem.disabled,
          })) as menuItemType[]
        )
      })
      .catch(() => {})
  }, [])

  useEffect(() => {
    setSelectedKeys([history.location.pathname.toLocaleLowerCase()])
  }, [history.location.pathname])

  /**
   * 切换侧边栏
   * @param pathName 路径名
   */
  const switchSideMenu = (pathName: string) => history.push(pathName)

  return (
    <Layout.Sider trigger={null} collapsible collapsed={collapsed}>
      <div className={styles.logo}>
        <span>智慧帮扶</span>
      </div>

      <Menu
        theme="dark"
        mode="inline"
        items={menuItemList}
        defaultSelectedKeys={[history.location.pathname]}
        selectedKeys={selectedKeys}
        onClick={({ key }) => switchSideMenu(key)}
      />
    </Layout.Sider>
  )
}

export default SideMenu
